
#include"golf.h"

// routines to compute hcp's

int countESCscores(int index)
{
    int i, cnt;

    cnt = 0;

    for (i = 0; i < HCP_WINDOW_LEN; i++)
        if ((int)players[index].ESCAdjustedScores[i] != NO_SCORE)
            cnt++;

    return (cnt);

}

void copyESCscores(int index, float buffer[])
{
    int i;

    for (i = 0; i < HCP_WINDOW_LEN; i++)
        buffer[i] = players[index].ESCAdjustedScores[i];
}

float getLowestScore(float buffer[])
{
    int i, lowIndex;
    float lowest = BIGNUM;
    float temp;

    for (i = 0; i < HCP_WINDOW_LEN; i++) {
        temp = buffer[i];
        if ((temp < lowest) && (temp != (float)NO_SCORE)) {
            lowest = temp;
            lowIndex = i;
        }
    }

    buffer[lowIndex] = NO_SCORE;    // flag that we took this score

    return (lowest);
}

void compute_hcps(int total_players)
{
    int i, j;
    float sum;
    int count;
    int tmp_int;
    float buffer[HCP_WINDOW_LEN];

    for (i = 1; i <= total_players; i++) {
        count = countESCscores(i);
        sum = 0.0;

        if (count == 0)
            players[i].curr_hcp = NO_HCP;
        else if (count <= BEST_HCP_SCORES)  // average all the scores the player has turned in
        {
            for (j = HCP_WINDOW_LEN - 1; j >= (HCP_WINDOW_LEN - count); j--)
                sum += players[i].ESCAdjustedScores[j];

            players[i].curr_hcp = (sum / (float)count) - (float)TOTAL_PAR;
            tmp_int = (int)(10 * players[i].curr_hcp + 0.5);
            players[i].curr_hcp = tmp_int / 10.0;
        } else                  // player has more than best_hcp_scores
        {
            copyESCscores(i, buffer);

            for (j = 0; j < BEST_HCP_SCORES; j++)
                sum += getLowestScore(buffer);

            players[i].curr_hcp =
                (sum / (float)BEST_HCP_SCORES) - (float)TOTAL_PAR;
            tmp_int = (int)(10 * players[i].curr_hcp + 0.5);
            players[i].curr_hcp = tmp_int / 10.0;
        }

    }

}
